package com.ruoyi.settled.helper;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

//测试python脚本
public class PythonCaller {
    public static void main(String[] args) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> inputData = new HashMap<>();
            inputData.put("order_amount", 2200);
            inputData.put("formula", "orderAmount * (1 - taxRate)");
            inputData.put("bonus_amount", null);
            inputData.put("commission_rate", 0.10);
            inputData.put("tax_rate", 0.1);

            // 指定临时文件存储目录
            File tempDir = new File("cold-chain-settled\\src\\main\\resources\\temp"); // 自定义目录
            if (!tempDir.exists()) {
                tempDir.mkdirs(); // 如果目录不存在，则创建
            }

            // 创建临时文件
            File tempFile = File.createTempFile("input", ".json", tempDir);
            String jsonFilePath = tempFile.getAbsolutePath();
            System.out.println("Temporary file path: " + jsonFilePath);

            // 将 JSON 数据写入临时文件
            objectMapper.writeValue(tempFile, inputData);

            // Python 脚本路径
            String scriptPath = "D:\\integration-cold-chain-front2\\cold-chain-settled\\src\\main\\resources\\settlement.py";

            // 调用 Python 脚本，传递临时文件路径
            ProcessBuilder processBuilder = new ProcessBuilder("python", scriptPath, jsonFilePath);
            processBuilder.redirectErrorStream(true); // 合并错误流到输出流
            Process process = processBuilder.start();

            // 读取标准输出
            BufferedReader stdOutput = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder output = new StringBuilder();
            String line;
            while ((line = stdOutput.readLine()) != null) {
                output.append(line);
            }

            // 读取标准错误输出
            BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            StringBuilder errorOutput = new StringBuilder();
            while ((line = stdError.readLine()) != null) {
                errorOutput.append(line);
            }

            // 等待 Python 脚本执行完成
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                throw new RuntimeException("Python script execution failed with exit code " + exitCode + ", error output: " + errorOutput.toString());
            }

            // 输出 Python 脚本的执行结果
            System.out.println("Output: " + output.toString());
            System.err.println("Error Output: " + errorOutput.toString());

            // 删除临时文件
            tempFile.delete();
            System.out.println("Temporary file deleted: " + jsonFilePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}